<template>
  <div class="f-body">
    <baidu-map  :center="center" :zoom="zoom" :double-click-zoom="false" :scroll-wheel-zoom="false" :min-zoom="5" :max-zoom="12" class="f-map" @ready="handler">
      <bm-control class="f-control">
        <el-button type="primary" size="small" icon="el-icon-refresh" @click="drawInit">刷新</el-button>
        <el-button type="primary" size="small"  icon="el-icon-back" @click="drawBack" v-if="showBack">返回</el-button>
      </bm-control>
      <bm-control class="f-control" anchor="BMAP_ANCHOR_TOP_RIGHT">
        <el-slider
          v-model="zoom"
          vertical
          :min="5"
          :max="12"
          height="80px"
          show-input>
        </el-slider>
      </bm-control>
    </baidu-map>
  </div>
</template>
<script>
  import {getGisMain, getGisChild, getGisJson} from '@/api/gis/gis'

  export default {
    data () {
      return {
        showBack: false,
        center: {lng: 109.404, lat: 39.915},
        zoom: 5,
        map: null,
        colorArr: ['#FEE9B2', '#E3FED1', '#D9F0FE', '#FBD4E6', '#F3D2AF', '#00FFFF', '#FFDC35', '#ffff60'],
        gisCode: [''],
        gisName: [''],
        gisTable: '',
        runLeve: 3
      }
    },
    methods: {
      handler ({BMap, map}) {
        this.map = map
        this.drawENWS()
        this.drawInit()
      },
      addZoom () {
        this.zoom = this.zoom + 1
      },
      cutZoom () {
        this.zoom = this.zoom - 1
      },
      drawInit () { // 初始化地图覆盖物
        let _gisCode = this.gisCode[this.gisCode.length - 1]
        if (this.gisCode.length === 1) {
          this.showBack = false
        } else {
          this.showBack = true
        }
        this.removeOverlay() // 清空图层
        // 判断是 全国 还是 某个省 某个市 某个县 某个村
        if (_gisCode === '') { // 全国 即所有省
          this.drawChina()
        } else if (_gisCode.length === 6 && _gisCode.slice(-4) === '0000') { // 省 即本省下面得所有市
          this.drawProvince()
        } else if (_gisCode.length === 6 && _gisCode.slice(-2) === '00') { // 市 即市下面得县或区
          this.drawCity()
        } else if (_gisCode.length === 6 && _gisCode.slice(-2) !== '00') { // 县或区 即下面得街道
          this.drawStreet()
        }
      },
      drawChina () { // 全国地图
        let params = {
          'code': ''
        }
        this.zoom = 5
        this.map.centerAndZoom(new BMap.Point(this.center.lng, this.center.lat), this.zoom) // 调整地图位置
        getGisMain(params).then((res) => {
          let _gisMainObj = res.data
          for (let i = 0; i < _gisMainObj.length; i++) {
            let color = this.getRandomColor() // this.colorArr[i % this.colorArr.length] // 填充色
            this.drawBoundary(this.map, _gisMainObj[i], color) // 画图
          }
        })
      },
      drawProvince () { // 省份地图
        let _gisCode = this.gisCode[this.gisCode.length - 1]
        let _gisName = this.gisName[this.gisName.length - 1]
        let params = {
          'code': _gisCode
        }
        getGisMain(params).then((res) => {
          let _gisMainObj = res.data
          this.gisTable = _gisMainObj[0].tableName
          this.drawChildBoundary(_gisMainObj[0].code, _gisMainObj[0].tableName) // 画图
          this.setViewByName(_gisName) // 调整视野
        })
      },
      drawCity () { // 市 即市下面得县或区
        let _gisCode = this.gisCode[this.gisCode.length - 1]
        let _gisName = this.gisName[this.gisName.length - 1]
        this.drawChildBoundary(_gisCode, this.gisTable) // 画图
        this.setViewByName(_gisName) // 调整视野
      },
      drawStreet () {
        let _gisCode = this.gisCode[this.gisCode.length - 1]
        let params = {
          'code': _gisCode
        }
        getGisJson(params).then((res) => {
          let data = eval(res.data)
          // 循环数据从中找出对应子集数据
          let viewportArr = []
          for (let i = 0; i < data.length; i++) {
            let color = this.getRandomColor() // this.colorArr[i % this.colorArr.length] // 填充色
            let ply = this.drawPolygonByJson(data[i], color) // 开始绘制多边形
            viewportArr = viewportArr.concat(ply.getPath()) // 所有点集合
            this.drawLabel(this.map, data[i].name, this.getCenterPoint(ply.getPath())) // 坐标点
          }
          this.setViewByPlayPath(viewportArr) // 调整视野
        })
      },
      drawPolygonByJson (data, color) { // 划多边形
        let that = this
        let pointArr = data.poly[0]
        let code = data.code
        let name = data.name
        // 定义一个新的数组用于返回数据
        let resArr = []
        // 循环数组数组
        for (let i = 0; i < pointArr.length; i++) {
          // 创建百度地理坐标点
          let point = new BMap.Point(pointArr[i][0], pointArr[i][1])
          resArr.push(point)
        }
        let play = new BMap.Polygon(resArr, {
          strokeWeight: 2,
          strokeColor: '#f00',
          fillColor: color,
          fillOpacity: 1
        }) // 建立多边形覆盖物
        play.addEventListener('click', function (res) { // 多边形点击事件
          if (that.gisCode.length < that.runLeve) {
            that.gisCode.push(code)
            that.gisName.push(name)
            that.drawInit()
          }
        })
        this.map.addOverlay(play)
        return play
      },
      drawChildBoundary (code, tblName) { // 获取下层得多边形数据
        let params = {
          'tblName': tblName,
          'fcode': code
        }
        getGisChild(params).then((res) => {
          let _gisMainObj = res.data
          for (let i = 0; i < _gisMainObj.length; i++) {
            let color = this.getRandomColor() // this.colorArr[i % this.colorArr.length] // 填充色
            this.drawBoundary(this.map, _gisMainObj[i], color)
          }
        })
      },
      setViewByPlayPath (playPath) { // 调整视野
        this.map.setViewport(playPath) // 调整视图
      },
      setViewByName (name) { // 调整视野
        let that = this
        let bdary = new BMap.Boundary()
        bdary.get(name, function (res) {
          var count = res.boundaries.length // 行政区域的点有多少个
          if (count === 0) {
            return
          }
          if (res) {
            var pointArray = []
            for (var i = 0; i < res.boundaries.length; i++) {
              let ply = new BMap.Polygon(res.boundaries[i]) // 建立多边形覆盖物
              pointArray = pointArray.concat(ply.getPath())
            }
            that.map.setViewport(pointArray)
          }
        })
      },
      drawENWS () { // 添加背景覆盖物
        let EN_JW = '180, 90;'
        let NW_JW = '-180,  90;'
        let WS_JW = '-180, -90;'
        let SE_JW = '180, -90;'
        // 东南西北四个角添加一个覆盖物
        let ply1 = new BMap.Polygon(['180, 90'] + SE_JW + SE_JW + WS_JW + NW_JW + EN_JW + SE_JW,
          { strokeOpacity: 0.5, strokeColor: '#ffffff', strokeWeight: 0.001, fillColor: '#ffffff', fillOpacity: 1 })
        this.map.addOverlay(ply1)
      },
      drawBoundary (map, obj, color) { // 根据地区名称获取行政区划边接
        let that = this
        let _bdaryMap = new BMap.Boundary()
        _bdaryMap.get(obj.name, function (rs) { // 获取行政区域
          let count = rs.boundaries.length
          for (let i = 0; i < count; i++) {
            let play = new BMap.Polygon(rs.boundaries[i], { strokeWeight: 2, strokeColor: '#ff0000', fillColor: color, fillOpacity: 1 }) // 建立多边形覆盖物
            play.addEventListener('click', function (res) { // 多边形点击事件
              if (that.gisCode.length < that.runLeve) {
                that.gisCode.push(obj.code)
                that.gisName.push(obj.name)
                that.drawInit()
              }
            })
            map.addOverlay(play) // 添加覆盖物
          }
          // 加入label
          that.drawLabel(map, obj.name)
        })
      },
      drawLabel (map, name, point) { // 中心点
        if (point) {
          var marker = new BMap.Marker(point)
          map.addOverlay(marker)
          var label = new BMap.Label(name, {offset: new BMap.Size(20, -10)})
          marker.setLabel(label)
        } else {
          // 创建地址解析器实例
          var myGeo = new BMap.Geocoder()
          // 将地址解析结果显示在地图上,并调整地图视野
          myGeo.getPoint(name, function (point) {
            if (point) {
              var marker = new BMap.Marker(point)
              map.addOverlay(marker)
              var label = new BMap.Label(name, {offset:new BMap.Size(20,-10)})
              marker.setLabel(label)
            }
          }, name)
        }
      },
      getCenterPoint (path) { // 获取中心点坐标
        var x = 0.0
        var y = 0.0
        for (let i = 0; i < path.length; i++) {
          x = x + parseFloat(path[i].lng)
          y = y + parseFloat(path[i].lat)
        }
        x = x / path.length
        y = y / path.length
        return new BMap.Point(x, y)
      },
      removeOverlay (e) { // 清空覆盖物
        this.map.clearOverlays()
        this.drawENWS()
      },
      drawBack (e) {
        if (this.gisCode.length > 1) {
          this.gisCode.pop()
          this.gisName.pop()
          this.drawInit()
        }
      },
      getRandomColor () {
         let color = '#' + Math.floor(Math.random() * 0xffffff).toString(16)
         return this.LightenDarkenColor(color, 50)
      },
      LightenDarkenColor (col, amt) {
        let usePound = false
        if (col[0] === '#') {
          col = col.slice(1)
          usePound = true
        }
        let num = parseInt(col, 16)
        let r = (num >> 16) + amt
        if (r > 255) r = 255
        else if (r < 0) r = 0
        let b = ((num >> 8) & 0x00FF) + amt
        if (b > 255) b = 255
        else if (b < 0) b = 0
        let g = (num & 0x0000FF) + amt
        if (g > 255) g = 255
        else if (g < 0) g = 0
        return (usePound ? '#' : '') + (g | (b << 8) | (r << 16)).toString(16)
      }
    }
  }
</script>
<style scoped>
  .f-map{
    width: 100%;
    height: 800px;
  }
  .f-control{
    margin:5px 10px;
  }

</style>
